package com.xian.im.modules.im.service.impl;

import com.xian.im.modules.im.controller.model.login.LoginReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xian.im.modules.im.dao.AccountDao;
import com.xian.im.modules.im.entity.AccountEntity;
import com.xian.im.modules.im.service.AccountService;

import java.util.Objects;

@Slf4j
@Service("accountService")
public class AccountServiceImpl extends ServiceImpl<AccountDao, AccountEntity> implements AccountService {

    /**
     * @param userId
     * @return
     */
    @Override
    public AccountEntity getEntityByUserId(Long userId) {
        return this.lambdaQuery().eq(AccountEntity::getUserId, userId).one();
    }

    /**
     * 登录
     * @param account
     * @return
     */
    @Override
    public AccountEntity getEntityByAccount(String account) {
        return this.lambdaQuery().eq(AccountEntity::getAccount,account).one();
    }

    /**
     * @param req
     * @return
     */
    @Override
    public Boolean checkLoginPermissions(LoginReq req) {
        AccountEntity entity = getEntityByAccount(req.getUserName());
        if (entity != null) {
            String salt = entity.getSalt();
            String md5 = MD5Encoder.encode((req.getPassword() + salt).getBytes());
            if(Objects.equals(entity.getPassword(),md5)){
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }
}